<?php

Raise::load('core.RaiseObject');
Raise::load('db.RaiseDbModel');
Raise::load('core.RaiseCollection');
Raise::load('db.RaiseDbSqlQueryCondition');
Raise::load('db.RaiseDbSqlIdentifier');

/**
 * RaiseDbSqlSelect class
 * represents an SQL SELECT statement
 *
 * @author Sam-Mauris Yong <hellclanner at live dot com>
 * @license http://www.opensource.org/licenses/bsd-license New BSD License
 * @package Raise.Core.DataAccess.Sql
 * @since 1.2
 */
class RaiseDbSqlSelect extends RaiseObject {

    /**
     * The model to load with
     * @var RaiseDbModel
     */
    private $model;

    /**
     * Collection of fields to retrieve in the result set
     * @var RaiseCollection
     */
    private $field;

    /**
     * The conditions for this select statement
     * @var RaiseDbSqlQueryCondition
     */
    private $condition;

    function __construct($m) {
        $this->model($m);
        $this->field = new RaiseCollection();
    }
    
    /**
     * Get or set the table which this statement is selecting from
     * @param string $m (optional) Set a new table
     * @return string
     */
    public function model($m = null){
        if(func_num_args() == 1){
            $this->model = $m;
        }
        return $this->model;
    }

    /**
     * Get or set the conditions for this select statement
     * @param RaiseDbSqlQueryCondition $c (optional) The new conditions for this select statement
     * @return RaiseDbSqlQueryCondition
     */
    public function condition($c = null){
        if(func_num_args() == 1){
            $this->condition = $c;
        }
        return $this->condition;
    }

    /**
     * Get collection of fields to return in the result set
     * @return RaiseCollection
     */
    public function field(){
        return $this->field;
    }

    public function __toString(){
        $q = 'SELECT ';

        $t = array();
        foreach($this->field as $f){
            $t[] = (string)$f;
        }
        if(count($t) == 0){
            $t[] = '*';
        }
        $q .= implode(', ', $t);
        $name = RaiseDbSqlIdentifier::field($this->model->table(), $this->model->connection());
        $q .= ' FROM ' . $name;

        if($this->condition){
            $q .= $this->condition->__toString();
        }
        return $q;
    }

}
